package com.example.tianling.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.tianling.common.utils.MinioUtils;
import com.example.tianling.common.utils.R;
import com.example.tianling.common.utils.RedisUtils;
import com.example.tianling.common.vo.WxUserVo;
import com.example.tianling.entity.UserEntity;
import com.example.tianling.service.ArticleService;
import com.example.tianling.service.UserService;
import com.example.tianling.service.WxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WxUserController {
    @Autowired
    private WxService wxService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private final static Logger logger = LoggerFactory.getLogger(WxUserController.class);

    @PostMapping("/wx_user/get_access_token")
    @ResponseBody
    public R getAccessToken() throws IOException {
        String accessToken = wxService.getAccessToken();
        return R.success(accessToken);
    }

    // 微信小程序用户登录
    @PostMapping("/wx_user/login")
    @ResponseBody
    public R WxLogin(@RequestBody String params) throws Exception {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        String code = paramsJSONObject.getString("code");

        WxUserVo wxUserVo = userService.wxLogin(code);

        return R.success(wxUserVo);
    }

    // 微信小程序用户手机号码注册
    @PostMapping("/wx_user/register")
    @ResponseBody
    public R WxRegister(@RequestBody String params) throws IOException {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        String code = paramsJSONObject.getString("code");
        String openId = paramsJSONObject.getString("openId");

        WxUserVo wxUserVo = userService.wxRegister(code, openId);

        if (wxUserVo != null) {
            return R.success(wxUserVo);
        }
        return R.error(400, "注册失败");
    }

    @RequestMapping(value = "/wx_user/message")
    @ResponseBody
    public String get(HttpServletRequest request, String signature, String timestamp, String nonce, String echostr) {
        logger.info(request.toString());
        logger.info(echostr);
        if(request.getMethod().equalsIgnoreCase("get")){//用来校验，一般会验证前端配置的token等，这里简化了代码。
            logger.info(echostr);
            return echostr;
        }else if(request.getMethod().equalsIgnoreCase("POST")){//接收用户的相关行为事件结果
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                StringBuilder requestContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    requestContent.append(line);
                }
                reader.close();
                logger.info(requestContent.toString());
                // 处理接收结果
                JSONObject json = JSON.parseObject(requestContent.toString());
                if (json.getString("MsgType").equals("event") && json.getString("Event").equals("wxa_media_check")) {
                    JSONObject result = json.getJSONObject("result");
                    logger.info(result.toJSONString());
                    if (result.getInteger("label") == 100) {
                        String traceId = json.getString("trace_id");
                        Map<String, Object> traceMap = redisUtils.get("trace_"+traceId, HashMap.class);
                        if (traceMap.get("type").equals("userImg")) {
                            // 获取redis中的信息
                            String imgUrl = traceMap.get("url").toString();
                            String userId = traceMap.get("userId").toString();
                            minioUtils.updateUserImg(imgUrl, userId);
                        } else if (traceMap.get("type").equals("articleImg")) {
                            articleService.updateImgNum(traceMap.get("articleId").toString());
                        }
                    }
                }
                return "";
            } catch (IOException e) {
                // 处理异常情况
                e.printStackTrace();
                logger.error("异常：" + e.getMessage());
                return e.toString();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else{
            logger.info("不是get 或 post方法");
            return null;
        }
    }
}

